package com.eightbears.beboy.ui.user.activity;

import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.FaceGVAdapter;
import com.eightbears.beboy.adapter.FacePageAdeapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.InputMethodUtils;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.gif.AnimatedGifDrawable;
import com.eightbears.beboy.base.view.gif.AnimatedImageSpan;
import com.eightbears.beboy.base.view.viperpager.CirclePageIndicator;
import com.eightbears.beboy.entity.HomeListEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_POST_COMMENT_LIST;
import static com.eightbears.beboy.ui.user.fragment.HomeFragment.PARAMS_POST_ITEM;

public class RepostPostActivity extends BaseActivity {

    public static final String EVENT_PARAMS_REPOST = "repost";
    public static final String EVENT_PARAMS_COMMENT = "comment";
    public static final String EVENT_PARAMS_LIKE = "like";
    public static final String EVENT_PARAMS_SHARE = "share";

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.et_post)
    EditText et_post;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.iv_user_head)
    ImageView iv_user_head;
    @BindView(R.id.tv_nickname)
    TextView tv_nickname;
    @BindView(R.id.tv_post)
    TextView tv_post;
    @BindView(R.id.rl_lock_layout)
    RelativeLayout rl_lock_layout;
    @BindView(R.id.iv_biaoqing)
    ImageView iv_biaoqing;
    @BindView(R.id.btn_publish)
    Button btn_publish;
    @BindView(R.id.view_face)
    View view_face;
    @BindView(R.id.vp_live_room_face)
    ViewPager vp_live_room_face;                      // 表情容器
    @BindView(R.id.cpi_live_room_indicator)
    CirclePageIndicator cpi_live_room_indicator;      // 表情分页
    @BindView(R.id.ll_repost_content)
    LinearLayout ll_repost_content;

    private HomeListEntity.Post post;

    private JSONArray faceJson;
    private List<String> faceName;                           // 表情名称
    private List<String> facePath;                           // 表情路径
    private String repost_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repost_post);

        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initData() {
        post = (HomeListEntity.Post) getExtras().get(PARAMS_POST_ITEM);

        if (post.isReport()) {
            tv_title.setText(R.string.text_repost_title);
        } else {
            tv_title.setText(R.string.text_comment_title);
            ll_repost_content.setVisibility(View.GONE);
        }

        if (post.getPrice() > 0)
            rl_lock_layout.setVisibility(View.VISIBLE);
        else
            rl_lock_layout.setVisibility(View.GONE);

        faceJson = CommonUtils.getFromAssets2Json("face/face.json", this);  // 取得表情
        faceName = new ArrayList<>();               // 表情名称
        facePath = new ArrayList<>();               //

        String imgUrl;
        if (null != post.getImages() && post.getImages().size() > 0) {
            imgUrl = post.getImages().get(0);
        } else if (null != post.getRepost() && null != post.getRepost().getImages()
                && post.getRepost().getImages().size() > 0) {
            imgUrl = post.getRepost().getImages().get(0);
        } else {
            imgUrl = R.mipmap.default_icon + "";
        }

        CommonUtils.loadImageView(this, imgUrl, R.mipmap.default_icon, iv_user_head);


        tv_nickname.setText("@" + post.getUser().getNickname());
        if (checkGifExist(post.getPost())) {
            tv_post.setText(handler(tv_post, post.getPost()));
        } else {
            tv_post.setText(post.getPost());
        }

        if (post.getRepost() == null)
            repost_id = post.getId() + "";
        else
            repost_id = post.getRepost().getId() + "";

        initFaceLayout();
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });

        et_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                view_face.setVisibility(View.GONE);
            }
        });


    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.btn_publish)
    void publishComment() {
        if (post.isReport()) {
            repost();
        } else {
            if (et_post.getText().toString().trim().equals("")) {
                ShowToast.showShortToast(getResources().getString(R.string.alert_input_empty));
                return;
            }
            comment();
        }

    }

    // 转发
    private void repost() {

        String postText = et_post.getText().toString().trim();
        if (TextUtils.isEmpty(postText)) {
            postText = "转发信息";
        }

        OkHttpUtils.post().url(URL_POST_COMMENT_LIST)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("post", postText)
                .addParams("category", "12")
                .addParams("price", "0")
                .addParams("city_id", SPUtil.getUserLocation().getCityId())
                .addParams("province_id", SPUtil.getUserLocation().getProvinceId())
                .addParams("district_id", SPUtil.getUserLocation().getDistrictId())
                .addParams("repost_id", repost_id)
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                EventBus.getDefault().post(EVENT_PARAMS_REPOST);
                finish();
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(RepostPostActivity.this, status_error);
            }
        });
    }

    /**
     * 评论
     */
    private void comment() {
        String url = URL_POST_COMMENT_LIST + post.getId() + "/comment";
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("post_id", post.getId() + "")
                .addParams("comment", et_post.getText().toString())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                EventBus.getDefault().post(EVENT_PARAMS_COMMENT);
                finish();
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(RepostPostActivity.this, status_error);
            }
        });
    }


    /**
     * 表情布局初始化
     */
    private void initFaceLayout() {
        for (int i = 0; i < faceJson.length(); i++) {
            try {
                JSONArray face = (JSONArray) faceJson.get(i);
                facePath.add((String) face.get(0));
                faceName.add((String) face.get(1));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        List<View> lv = new ArrayList<>();
        lv.add(viewPagerItem());
        FacePageAdeapter adapter = new FacePageAdeapter(lv);
        vp_live_room_face.setAdapter(adapter);
        vp_live_room_face.setCurrentItem(0);
        cpi_live_room_indicator.setViewPager(vp_live_room_face);
    }

    private View viewPagerItem() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.face_gridview, null);
        GridView gridview = (GridView) layout.findViewById(R.id.chart_face_gv);
        FaceGVAdapter mGvAdapter = new FaceGVAdapter(facePath, faceName, this);
        gridview.setAdapter(mGvAdapter);
        gridview.setNumColumns(7);
        // 单击表情执行的操作
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    String png = ((TextView) ((LinearLayout) view).getChildAt(1)).getText().toString();
                    String facePath = ((TextView) ((LinearLayout) view).getChildAt(2)).getText().toString();
                    insert(getFace(facePath, png));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        return gridview;
    }

    /**
     * 向输入框里添加表情
     */
    private void insert(CharSequence text) {
        int iCursorStart = Selection.getSelectionStart((et_post.getText()));
        int iCursorEnd = Selection.getSelectionEnd((et_post.getText()));
        if (text.length() + iCursorStart > 200) {
            return;
        }
        if (iCursorStart != iCursorEnd) {
            (et_post.getText()).replace(iCursorStart, iCursorEnd, "");
        }
        int iCursor = Selection.getSelectionEnd((et_post.getText()));
        (et_post.getText()).insert(iCursor, text);
    }

    private SpannableStringBuilder getFace(String facePath, String faceName) {
        SpannableStringBuilder sb = new SpannableStringBuilder();
        try {
            String filePath = "face/" + facePath;
            String tempText = faceName;
            sb.append(tempText);
            sb.setSpan(new ImageSpan(this, BitmapFactory.decodeStream(getAssets().open(filePath))),
                    sb.length() - tempText.length(), sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sb;
    }

    private boolean checkGifExist(String message) {
        String regex = "(\\[[a-z]*[^\\[\\u0000-\\u007F\\]]+\\])";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(message);
        if (m.find()) {
            return true;
        } else {
            return false;
        }
    }


    // 对文字处理后显示
    private SpannableStringBuilder handler(final TextView gifTextView, String content) {

        if (faceJson == null) {
            faceJson = CommonUtils.getFromAssets2Json("face/face.json", mContext);
        }
        SpannableStringBuilder sb = new SpannableStringBuilder(content);
        String regex = "(\\[[a-z]*[^\\[\\u0000-\\u007f\\]]+\\])";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        while (m.find()) {
            for (int i = 0; i < faceJson.length(); i++) {
                try {
                    JSONArray arr = (JSONArray) faceJson.get(i);
                    String faceTemp = arr.get(1).toString();
                    if (faceTemp.equals(m.group())) {
                        String gif = "face/" + arr.get(0);
                        InputStream is = mContext.getAssets().open(gif);
                        sb.setSpan(new AnimatedImageSpan(new AnimatedGifDrawable(is, new AnimatedGifDrawable.UpdateListener() {
                            @Override
                            public void update() {
                                gifTextView.postInvalidate();
                            }
                        })), m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        is.close();
                    }
                } catch (JSONException | IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb;
    }

    @OnClick(R.id.iv_biaoqing)
    void showFace() {
        if (view_face.getVisibility() == View.VISIBLE) {
            view_face.setVisibility(View.GONE);
            InputMethodUtils.showInputMethod(et_post, 0);
        } else {
            InputMethodUtils.closeInputMethod(this, et_post);
            view_face.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void finish() {
        super.finish();
        InputMethodUtils.closeInputMethod(this, et_post);
    }
}
